package upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.axis.encoding.Base64;

public class UploadService implements IUploadService {
	private static Properties p = new Properties();
	static{
		String path = "/upload.properties";
		InputStream inStream = null;
		try {
			inStream = UploadService.class.getResourceAsStream(path);
			p.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String upload(String fileName,String encodedFileString) {  
		String dir = p.getProperty("uploadDir");
        FileOutputStream fos = null;   
        
        File file = new File(dir + fileName);  
        File parentFile = file.getParentFile();
        if(!parentFile.exists()) {
        	parentFile.mkdirs();
        }
     
        byte[] bytes = Base64.decode(encodedFileString);   
        try {   
        	if(!file.isFile()){
    			file.createNewFile();
            }
            fos = new FileOutputStream(file);   
            fos.write(bytes);   
            fos.flush();     
        } catch (IOException e) {   
        	e.printStackTrace();
            return "Wrong!";   
        }finally{
        	try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
				return "Wrong!";  
			} 
        }
        return "Success!";   
    }   
	
	public static void main(String[] args) {
		System.out.println(p.getProperty("uploadDir"));
		
		IUploadService uploadService = new UploadService();
		String str = "afdgdg";
		uploadService.upload("test.txt", Base64.encode(str.getBytes()));
		
	}

}
